package com.woniuxy.project115.kaer.platform.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.project115.kaer.platform.dto.PermissionTypeTreeDto;
import com.woniuxy.project115.kaer.platform.entity.Permission;
import com.woniuxy.project115.kaer.platform.mapper.PermissionMapper;
import com.woniuxy.project115.kaer.platform.service.PermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.management.relation.Role;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fyy
 * @since 2025年02月23日
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {
    @Resource
    private PermissionMapper permissionMapper;
    @Override
    public List<Permission> getAllPermission() throws Exception {
        //查询所有权限
        List<Permission> permissionList = permissionMapper.selectList(null);
        //判断是否为空
        if(permissionList == null || permissionList.size() == 0){
            throw new Exception("权限列表为空");
        }
        //返回权限列表
        return permissionList;
    }

    @Override
    public List<PermissionTypeTreeDto> getAllChildPermission() {
        //查询所有一级类别菜单
        final QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",0);
        final List<Permission> permissionList1 = permissionMapper.selectList(wrapper);
        //创建一个最终返回值的集合
        final List<PermissionTypeTreeDto> permissionTypeTreeDtoList = new ArrayList<>();
        //将rolePermissionDtoList集合转换为dto，方便根据id查询子权限
        for (Permission permission : permissionList1){
            final PermissionTypeTreeDto treeDto = BeanUtil.toBean(permission, PermissionTypeTreeDto.class);
            //调用递归查询子权限
            findChildren(treeDto);
            permissionTypeTreeDtoList.add(treeDto);
        }
        return permissionTypeTreeDtoList;
    }

    private void findChildren(PermissionTypeTreeDto treeDto){
        final QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",treeDto.getId());
        final List<Permission> permissionList2 = permissionMapper.selectList(wrapper);
            for (Permission permission : permissionList2){
                final PermissionTypeTreeDto child = BeanUtil.toBean(permission, PermissionTypeTreeDto.class);
                if (treeDto.getChildren() == null){
                    treeDto.setChildren(new ArrayList<>());
                }
                //调用递归查询子权限
                treeDto.getChildren().add(child);
                findChildren(child);
            }
    }
}
